package com.jiayi.comm.util;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;

public class PropertyFactory {

	private static java.util.Properties pros = new java.util.Properties();

	public PropertyFactory(List<String> filePaths)
	{
		if(filePaths!=null){
			for(int i=0;i<filePaths.size();i++){
				String filePath = filePaths.get(i);
				InputStream in = null;
				URL url = Thread.currentThread().getContextClassLoader().getResource(filePath);
				if (null == url)
				{
					url = this.getClass().getClassLoader().getResource(filePath);
				}
				if(null == url){
					url = this.getClass().getResource(filePath);
				}
				
				//解决文件路径可能出现空格的问题
				String path = url.getFile();
				if(!"".equals(path)){
					path = path.replace("%20", " ");
				}
				
				try
				{
					in = new BufferedInputStream(new FileInputStream(path));
					pros.load(in);
				}
				catch (Exception e)
				{
				}
				finally
				{
					if(in != null)
					{
						try
						{
							in.close();
						}
						catch (IOException e)
						{
						}
					}
				}
			}
		}
		
	}


	public HashMap<String, String> readProperty(String path, String fileName)
	{
		HashMap<String, String> map = new HashMap<String, String>();
		InputStream in = null;
		java.util.Properties p = new java.util.Properties();
		URL url = Thread.currentThread().getContextClassLoader().getResource(path + fileName);
		if (null == url)
		{
			url = this.getClass().getClassLoader().getResource(path + fileName);
		}
		
		//解决文件路径可能出现空格的问题
		String filepath = url.getFile();
		if(!"".equals(filepath)){
			path = path.replace("%20", " ");
		}
		
		try
		{
			in = new BufferedInputStream(new FileInputStream(filepath));
			p.load(in);
			Enumeration<?> e = p.propertyNames();
			while (e.hasMoreElements())
			{
				String key = (String) e.nextElement();
				String ruleStr = p.getProperty(key);
				map.put(key, ruleStr);
			}
		}
		catch (Exception e)
		{
			System.out.println("加载验证文件出错 ：");
		}
		finally
		{
			if(in != null)
			{
				try
				{
					in.close();
				}
				catch (IOException e)
				{
					System.out.println("关闭输入流出错 ：\n");
				}
			}
		}
		
		return map;
	}

	
	/**
	 * 重新加载/config.properties配置信息。
	 * 
	 */
	public synchronized void reloadProperties()
	{
		HashMap<String, String> properties = this.readProperty("", "/config.properties");
		this.pros.putAll(properties);
	}
	
	public static String getProperty(String key)
	{
		return pros.getProperty(key);
	}

	public void setProperty(String key, String value)
	{
		pros.setProperty(key, value);
	}
}
